<template>
  <div class="closing">
    <div>
      <jc-button
        :btn-arr="['reload', 'voucher', bomCost('createReceivableBill') && 'newy', 'sub', !list.length && 'check',
                   'option', 'remove', 'pass', 'push', 'batchFill']"
        :disab-arr="['close', 'cancel', 'copy', 'com1', 'com2', 'using', 'freeze']"
        :fbillno="fbillNo"
        url="tFinReceivable/queryReceivableList"
        @refresh="handleGetUntreated"
        @newly="newly"
        @submit="submit(1)"
        @noSubmit="submit(2)"
        @audit="audit(1)"
        @noAudit="audit(2)"
        @del="remove"
        @toExcel="handleExport"
        @check="check('up')"
        @check1="check('down')"
        @voucher="voucherVis=true"
        @voucherLok="LooktialsTask"
        @pushDown="isdanjuDialog=true"
      />
    </div>
    <div class="header">
      <div class="header-name">
        <search
          :options="selectData"
          :search-son="searchSon"
          :msg="tacitly"
          @seek="collect"
          @hand="handleQuerySonClass"
        />
        <el-button type="primary" class="btn" size="mini" @click="handleQuerySonClass">{{ $t('btn.search') }}</el-button>
        <filtration
          :ftype="ftype"
          :msg="tacitly"
          :select-data="selectData"
          :table-header="tableHeader1"
          :detail-header="tableHeader"
          @seachData="handleQuerySonClass"
        />
      </div>
    </div>
    <div class="table-content">
      <jc-table
        v-loading="loading"
        :table-data="tableData"
        :table-header="tableHeader"
        :table-height="tableHeight"
        sortable
        table-selection
        get-row-keys="fentryId"
        :get-summaries="getSummaries"
        show-summary
        @clickRow="particulars"
        @selectionChange="selectionDatas"
      >
        <template v-slot:tagSlot="col">
          <el-link type="primary" @click="particulars(col.scope.row)">{{ col.scope.row.fbillno }}</el-link>
        </template>
        <!--    物料编码    -->
        <template v-slot:orderSlot="col">
          <el-link type="primary" @click="jumpMateriel(col.scope.row)">
            {{ col.scope.row.fnumber }}
          </el-link>
        </template>
        <!--审核状态-->
        <template v-slot:btnState="clo">
          <span v-if="clo.scope.row.fdocumentstatus === ''" />
          <el-tag v-else :type="clo.scope.row.stateColor">{{ clo.scope.row.fdocumentstatus }}</el-tag>
        </template>
        <!--关闭状态-->
        <template v-slot:btnStates="col">
          <span v-if="col.scope.row.fclosestatus === ''" />
          <el-tag v-else :type="col.scope.row.closeColor">{{ col.scope.row.fclosestatus }}</el-tag>
        </template>
        <!--  操作  -->
        <template v-slot:btnSlot="col">
          <el-button size="mini" type="primary" @click="particulars(col.scope.row)">{{ $t('market.detail') }}</el-button>
        </template>
      </jc-table>
    </div>
    <!--  分页器  -->
    <div class="footer">
      <jc-pagination
        :total="total"
        :page.sync="currentPage"
        :limit.sync="size"
        @pagination="handleGetUntreated"
      />
    </div>
    <el-dialog
      v-dialogDrag
      :title="$t('market.checkBill')"
      model
      :visible.sync="isdanjuDialog"
      :close-on-click-modal="false"
      width="600px"
      center
      append-to-body
    >
      <div style="text-align: center;height: 100px;line-height: 100px">
        <el-radio-group v-model="orderLX">
          <el-radio v-for="item in receipts" :key="item" :label="item">{{ item }}</el-radio>
        </el-radio-group>
      </div>
      <hr>
      <span slot="footer" class="dialog-footer">
        <el-button size="mini" @click="isdanjuDialog = false">{{ $t('btn.cancel') }}</el-button>
        <el-button size="mini" type="primary" @click="pushDownOrder()">{{ $t('btn.confirm') }}</el-button>
      </span>
    </el-dialog>
    <upDown v-if="upDownVis" :msg="cha" :fentryid="EntryIds" @client="upDownVis=false" />
    <voucherPopup v-if="voucherVis" :enum-id="22" @voucher="credentialsTask" />
  </div>
</template>

<script>
import {
  pushToFinPayment, queryReceivableList, notsubmitReceivables, pushToFinReceipt,
  submitReceivables, reviewReceivables, notreviewReceivables, delReceivables, createBillVoucherTask
} from '@/api/financial/cashier'
import search from '@/components/Search'
import searData from '@/components/Search/mixin'
import { toMxBmina, CloseId } from '@/components/ToMxamineState'
import { export_json_to_excel, formatJson } from '@/utils/Export2Excel'
import filtration from '@/components/filtration'
import jcButton from '@/components/Button'

export default {
  name: 'ReceivableList',
  components: {
    voucherPopup: () => import('@/views/financial/cashier/receivable/components/voucherPopup'),
    upDown: () => import('@/components/upDown'),
    search,
    filtration,
    jcButton
  },
  mixins: [searData],
  props: {
    list: {
      type: Array,
      default: function() {
        return []
      }
    }
  },
  data() {
    return {
      upDownVis: false,
      voucherVis: false,
      cha: '',
      EntryIds: [],
      isdanjuDialog: false,
      orderLX: this.$t('menu.payment'),
      receipts: [this.$t('menu.payment'), this.$t('menu.proceeds')], // '付款单' 收款单
      ftype: 40,
      total: 0, // 总条目
      currentPage: 1, // 当前页
      size: 200, // 每页显示多少条数据
      fbillNo: '',
      // 表头
      tableData: [], // 销售数据
      tableHeight: '70vh',
      tableHeader: [
        { label: this.$t('market.coding'), type: 'tag', prop: 'fbillno', width: '120' },
        { label: this.$t('market.billType'), prop: 'fbilltypName', width: '100' },
        { label: this.$t('market.orderDate'), prop: 'fdate', width: '80' },
        { label: this.$t('market.documentstatus'), type: 'state', prop: 'fdocumentstatus', width: '100' },
        { label: this.$t('market.closeState'), type: 'states', prop: 'fclosestatus', width: '80' },
        { label: this.$t('market.settleCurr'), prop: 'fcurrencyName', width: '80' },
        { label: this.$t('market.cust'), prop: 'fcustName', width: '120' },
        { label: this.$t('market.frombillNo'), prop: 'frombillno', width: '100' },
        { label: this.$t('market.order'), prop: 'salKhddh', width: '120' },
        { label: this.$t('market.chargeQty'), prop: 'fcalQty', width: '80', align: 'right' },
        { label: this.$t('market.funit'), prop: 'funitName', width: '80' },
        { label: this.$t('market.fprice'), prop: 'fprice', width: '80', align: 'right' },
        { label: this.$t('market.ftaxPrice'), prop: 'ftaxprice', width: '80', align: 'right' },
        { label: this.$t('market.billallamount'), prop: 'fallamount', width: '80', align: 'right' },
        { label: this.$t('market.ftaxRate'), prop: 'ftaxrate', width: '80', align: 'right' },
        { label: this.$t('market.fmaterial'), type: 'order', prop: 'fnumber', width: '110' },
        { label: this.$t('shop.fname2'), prop: 'materialName', width: '100' },
        { label: this.$t('market.fdescripTion'), prop: 'fdescription', minWidth: '200' }
        // { label: this.$t('market.handle'), type: 'btn', width: '100' }
      ],
      selectVal: [],
      tableHeader1: [
        { label: this.$t('market.creator'), prop: 'fcreator' }
      ]
    }
  },
  created() {
    this.handleGetUntreated()
    this.tableHeader1 = this.tableHeader.concat(this.tableHeader1)
    this.tableHeight = window.innerWidth > 1440 ? 'calc(100vh - 230px)' : '73vh'
  },
  methods: {
    // 导出表格
    handleExport() {
      require.ensure([], () => {
        const tHeader = this.tableHeader.map((res) => {
          return res.label
        })
        const filterVal = this.tableHeader.map((res) => {
          return res.prop
        })
        if (this.tableData.length <= 0) {
          this.$message.warning('没有导出数据')
        } else if (this.val && this.val.length > 0) {
          const list = this.val.map(item => {
            return (toMxBmina(item), CloseId(item))
          })
          const data = formatJson(filterVal, list)
          export_json_to_excel(tHeader, data, '应收单列表')
        } else {
          queryReceivableList({
            pageSize: 100000,
            pageNum: 1,
            search: this.searCollData
          }).then(res => {
            if (res.code === 0) {
              const list = res.data.list.map(item => {
                return (toMxBmina(item), CloseId(item))
              })
              const data = formatJson(filterVal, list)
              export_json_to_excel(tHeader, data, '应收单列表')
            } else {
              this.$confirm(res.message, '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'error'
              })
            }
          })
        }
      })
    },
    // 获取应付单列表数据
    async handleGetUntreated(ev) {
      this.loading = true
      this.details = []
      if (ev && !ev.page) {
        this.details = ev
      }
      //
      const DATA = {
        list: this.list,
        pageNum: this.currentPage,
        pageSize: this.size,
        search: this.searCollData.concat(this.details)
      }
      const RES = await queryReceivableList(DATA)
      if (RES.code === 0) {
        this.loading = false
        this.tableData = RES.data.list.map(item => {
          return (toMxBmina(item), CloseId(item))
        })
        this.total = RES.data.total
      } else {
        this.loading = false
        this.$confirm(RES.message, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'error'
        })
      }
    },
    // 全选
    selectionDatas(val) {
      this.selectVal = []
      this.EntryIds = []
      this.SoucrceIds = []
      this.fbillNo = val[0].fbillno
      this.voucherid = val[0].voucherid
      this.taskFdate = []
      this.rates = []
      this.currId = []
      val.forEach(res => {
        this.rates.push(res.fexchangerate + '' || '0')
        res.fbillno && this.selectVal.push(res.fbillno)
        res.fdate && this.taskFdate.push(res.fdate)
        this.EntryIds.push(res.fentryId)
        this.currId.push(res.fsettlecurrId)
        res.fid && this.SoucrceIds.push(res.fid)
      })
    },
    // 公共函数
    toExamineFun(api) {
      const DATA = { Numbers: this.selectVal }
      api(DATA).then(res => {
        if (res.code !== 0) {
          this.$confirm(res.message, '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'error'
          })
          return
        }
        this.handleGetUntreated()
        this.selectVal = []
        this.innerHTM = ''
        res.data.forEach(res => {
          this.innerHTM += '<div>' + res + '</div>'
        })
        this.$notify.warning({
          title: '提示',
          message: this.innerHTM,
          duration: 3000, offset: 50,
          dangerouslyUseHTMLString: true
        })
      })
    },
    // 提交
    submit(ev) {
      const api = ev === 1 ? submitReceivables : notsubmitReceivables
      this.toExamineFun(api)
    },
    // 审核
    audit(ev) {
      const api = ev === 1 ? reviewReceivables : notreviewReceivables
      this.toExamineFun(api)
    },
    // 删除
    remove() {
      this.$confirm('确定要删除该订单么？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        const api = delReceivables
        this.toExamineFun(api)
      })
    },
    // 下推付款单
    pushDownOrder() {
      const DATA = {
        SoucrceIds: Array.from(new Set(this.SoucrceIds)),
        EntryIds: Array.from(new Set(this.EntryIds))
      }
      if (this.orderLX === this.$t('menu.payment')) {
        pushToFinPayment(DATA).then(res => {
          if (res.code === 0) {
            this.$router.push({
              path: `/paymentDetail/${res.data.fid}`
            })
            this.isdanjuDialog = false
          } else {
            this.$confirm(res.message, '提示', {
              dangerouslyUseHTMLString: true,
              confirmButtonText: '确定',
              type: 'error'
            })
          }
        })
      } else if (this.orderLX === this.$t('menu.proceeds')) {
        pushToFinReceipt(DATA).then(RES => {
          if (RES.code === 0) {
            this.$router.push({
              path: `/proceeDetail/${RES.data.fid}`
            })
          } else {
            this.$confirm(RES.message, '提示', {
              confirmButtonText: '确定',
              cancelButtonText: '取消',
              type: 'error'
            })
          }
        })
      }
      this.isdanjuDialog = false
    },
    // 搜索
    handleQuerySonClass(ev) {
      this.currentPage = 1
      if (ev && ev.fname) {
        this.searchSon = ev.detail
        this.customHandle(ev)
        this.handleGetUntreated(ev.detail)
      } else {
        this.handleGetUntreated()
      }
    },
    // 新增
    newly() {
      this.$router.push({ path: '/createReceivable' })
    },
    // 详情
    particulars(ev) {
      this.$router.push({ path: `/receivableDetail/${ev.fid}` })
    },
    // 上查、下查
    check(ev) {
      if (this.EntryIds.length === 0) return
      this.cha = ev
      this.upDownVis = true
    },
    // 凭证生成
    credentialsTask(ev) {
      this.voucherVis = false
      if (!ev) return
      const { fperiod, fgenerate, fmatching } = ev
      const DATA = {
        fids: Array.from(new Set(this.SoucrceIds)),
        fsettlecurrId: this.currId,
        fgenerate, fmatching, fperiod,
        fdate: this.taskFdate,
        fexchangerates: this.rates,
        enumId: 22, // 应收单
        mouldId: 57
      }
      createBillVoucherTask(DATA).then(res => {
        if (res.code === 0) {
          this.$message({ showClose: true, message: res.message, type: 'success' })
          this.$router.push({ path: '/certificate' })
        } else {
          this.$confirm(res.message, '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'error'
          })
        }
      })
    },
    // 查看凭证
    LooktialsTask() {
      const id = this.voucherid
      if (id) {
        this.$router.push({ path: `/certificateDetail/${id}` })
      } else {
        this.$confirm('该单据未能查询到对应的业务凭证！', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'error'
        })
      }
    },
    // 自定义列表
    customHandle(ev) {
      this.tableHeaders = []
      if (ev.header) {
        ev.header.forEach(item => {
          this.tableHeader1.forEach(res => {
            if (res.label === item) {
              this.tableHeaders.push(res)
            }
          })
        })
        this.tableHeader = this.tableHeaders
      } else if (ev.fname === '缺省方案') {
        this.tableHeader = this.oldTabHeader
      } else {
        this.tableHeader = this.tableHeader1
      }
    }
  }
}
</script>
<style lang="scss" scoped>
.closing {
  @include listBom;

  .header{
    position:relative;
    .header-name{
      width: 100%;
    }
    .btn{
      transform: translateY(18%);
      margin-left: 450px!important;
    }
  }
}
</style>
